package com.yx.yinshanjinniu.activitys;


import static com.yx.yinshanjinniu.utils.RouteUtil.gotoActivity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.Entry;
import com.google.android.material.appbar.AppBarLayout;
import com.yuruiyin.appbarlayoutbehavior.AppBarLayoutBehavior;
import com.yx.yinshanjinniu.R;
import com.yx.yinshanjinniu.adapters.FollowOrderAdapter;
import com.yx.yinshanjinniu.adapters.MarketDefaultPagerAdapter;
import com.yx.yinshanjinniu.adapters.MarketGoodsAdapter;
import com.yx.yinshanjinniu.application.MyApplication;
import com.yx.yinshanjinniu.base.BaseActivity;
import com.yx.yinshanjinniu.base.BaseRVAdapter;
import com.yx.yinshanjinniu.bean.FollowOrderBean;
import com.yx.yinshanjinniu.constants.Constant;
import com.yx.yinshanjinniu.eventbus.EventCenter;
import com.yx.yinshanjinniu.eventbus.EventConstants;
import com.yx.yinshanjinniu.net.ActionCallbackListener;
import com.yx.yinshanjinniu.utils.DataUtils;
import com.yx.yinshanjinniu.utils.FastClickUtil;
import com.yx.yinshanjinniu.utils.GlideUtils;
import com.yx.yinshanjinniu.utils.LogUtil;
import com.yx.yinshanjinniu.utils.RouteUtil;
import com.yx.yinshanjinniu.utils.ToastUtil;
import com.yx.yinshanjinniu.utils.ToolbarUtils;
import com.yx.yinshanjinniu.utils.Utils;
import com.yx.yinshanjinniu.view.CreateOrderModule;
import com.yx.yinshanjinniu.view.PromptDialog;
import com.zc.mychart.chart.MyChartCallBack;
import com.zc.mychart.chart.MyChartListener;
import com.zc.mychart.chart.MyKView;
import com.zc.mychart.model.EntryData;
import com.zc.mychart.model.GoodsAllBean;
import com.zc.mychart.model.GoodsItemBean;
import com.zc.mychart.model.KTimeType;
import com.zc.mychart.model.KViewMode;
import com.zc.mychart.utils.ArithUtil;
import com.zc.mychart.utils.FormatUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MarketNewActivity extends BaseActivity implements View.OnClickListener, MyChartListener, RadioGroup.OnCheckedChangeListener {
    private ImageView iv_back, iv_enter_left, iv_enter_right, iv_detail, iv_buy_up, iv_buy_down, iv_easy_top;
    private TextView tv_goods_change_range, tv_new_goods_price, tv_change_range, tv_new_price, tv_title, tv_new_goods_price_easy, tv_goods_change_range_easy, tv_empty, tv_open_easy, tv_close_easy, tv_high_easy, tv_low_easy, tv_easy_top, tv_open, tv_close, tv_low, tv_high;
    private RecyclerView rv_goods_easy, rv_follow_list;
    private View tool_bar;
    private NestedScrollView nsc_scroll;
    private View view_bg;
    private MyKView mKView;
    private RadioGroup rg_tab_detail;
    private MarketGoodsAdapter marketGoodsAdapter;
    private String mCurrentPro_code;//当前合约code
    private GoodsAllBean mGroupBean;//当前合约
    private List<GoodsItemBean> goods_list;//当前商品列表
    private GoodsItemBean mCurrentItemBean;//当前商品详情
    private int mDetailPosition = 0;//底部tab
    private int mCurrentGoodsPosition;
    private FollowOrderAdapter mRVAdapter;
    private List<FollowOrderBean> mFollowOrderList;//跟单列表
    private boolean isScroll;//是否在滑动
    private AppBarLayoutBehavior behavior;
    private CoordinatorLayout mCoordinatorLayout;
    private AppBarLayout mAppBarLayout;
    private LinearLayout ll_create_order, ll_default, ll_easy, ll_easy_top, ll_night_top, ll_tab_unit_price, ll_tab_goods;
    private ViewPager vp_goods_detail;
    private TextView rl_close_market;
    private List<GoodsAllBean> allList;
    private KTimeType mKTimeType = KTimeType.MIN1;//k线图类型
    private boolean mKLineRefresh = false;
    private SimpleDateFormat hmTimeFormat = new SimpleDateFormat("HH:mm", Locale.CHINA);
    private int mCurrentKLineIndex;
    private List<Entry> mEntries;//存放数据
    private boolean mFirstNowZero = true;
    private List<List<Object>> mKLineList;
    private int mIndexOffset = 5;
    private MyChartCallBack mChartCallBack;
    private int mApiType;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd", Locale.CHINA);
    private SimpleDateFormat timeFormat = new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA);
    private boolean mIsNight;
    private int bgColor;
    private int bgTradeColor;
    private int textColor;
    private boolean mIsEasy = true;
    private MarketDefaultPagerAdapter marketDefaultPagerAdapter;
    private int mTabIndex;//商品原料tab的index
    private AnimationSet showAnimation = null;
    private AnimationSet hideAnimation = null;
    private final long DURATION_TIME = 300;
    private double cacheLatestPrice;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mCurrentPro_code = bundle.getString(RouteUtil.BUNDLE_PRO_CODE);
        }

        if (TextUtils.isEmpty(mCurrentPro_code)) return;
        initData();
        initGoods();
        initKLine();
        showLatestPrice();
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_market_new;
    }

    @Override
    protected void findViews() {
        iv_back = findViewById(R.id.iv_back);
        tv_title = findViewById(R.id.tv_title);
        tool_bar = findViewById(R.id.tool_bar);
        iv_enter_left = findViewById(R.id.iv_enter_left);
        iv_enter_right = findViewById(R.id.iv_enter_right);
        tv_new_goods_price_easy = findViewById(R.id.tv_new_goods_price_easy);
        tv_goods_change_range_easy = findViewById(R.id.tv_goods_change_range_easy);
        rv_goods_easy = findViewById(R.id.rv_goods_easy);
        mKView = findViewById(R.id.mKView);
        rg_tab_detail = findViewById(R.id.rg_tab_detail);
        iv_detail = findViewById(R.id.iv_detail);
        tv_empty = findViewById(R.id.tv_empty);
        rv_follow_list = findViewById(R.id.rv_follow_list);
        iv_buy_up = findViewById(R.id.iv_buy_up);
        iv_buy_down = findViewById(R.id.iv_buy_down);
        tv_open_easy = findViewById(R.id.tv_open_easy);
        tv_close_easy = findViewById(R.id.tv_close_easy);
        tv_high_easy = findViewById(R.id.tv_high_easy);
        tv_low_easy = findViewById(R.id.tv_low_easy);
        mCoordinatorLayout = findViewById(R.id.coordinatorLayout);
        mAppBarLayout = findViewById(R.id.appbar_layout);
        ll_create_order = findViewById(R.id.ll_create_order);
        rl_close_market = findViewById(R.id.rl_close_market);
        ll_default = findViewById(R.id.ll_default);
        ll_easy = findViewById(R.id.ll_easy);
        ll_easy_top = findViewById(R.id.ll_easy_top);
        ll_night_top = findViewById(R.id.ll_night_top);
        vp_goods_detail = findViewById(R.id.vp_goods_detail);
        iv_easy_top = findViewById(R.id.iv_easy_top);
        tv_easy_top = findViewById(R.id.tv_easy_top);
        ll_tab_unit_price = findViewById(R.id.ll_tab_unit_price);
        ll_tab_goods = findViewById(R.id.ll_tab_goods);
        tv_new_price = findViewById(R.id.tv_new_price);
        tv_change_range = findViewById(R.id.tv_change_range);
        tv_new_goods_price = findViewById(R.id.tv_new_goods_price);
        tv_goods_change_range = findViewById(R.id.tv_goods_change_range);
        tv_open = findViewById(R.id.tv_open);
        tv_close = findViewById(R.id.tv_close);
        tv_low = findViewById(R.id.tv_low);
        tv_high = findViewById(R.id.tv_high);
        nsc_scroll = findViewById(R.id.nsc_scroll);
        view_bg = findViewById(R.id.view_bg);
        ToolbarUtils.setToolbarHeight(this, tool_bar);
        setPriceAnimtion();
    }

    @Override
    protected void setListeners() {
        iv_back.setOnClickListener(this);
        iv_enter_left.setOnClickListener(this);
        iv_enter_right.setOnClickListener(this);
        rg_tab_detail.setOnCheckedChangeListener(this);
        iv_buy_up.setOnClickListener(this);
        iv_buy_down.setOnClickListener(this);
        ll_tab_unit_price.setOnClickListener(this);
        ll_tab_goods.setOnClickListener(this);
        rv_follow_list.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    isScroll = false;
                } else {
                    isScroll = true;
                }
            }
        });

        ll_easy_top.setOnClickListener(this);
        ll_night_top.setOnClickListener(this);
        vp_goods_detail.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (marketDefaultPagerAdapter != null) {
                    mCurrentGoodsPosition = position;
                    marketDefaultPagerAdapter.setPosition(mCurrentGoodsPosition);
                    mCurrentItemBean = goods_list.get(mCurrentGoodsPosition);
                    String goodMoney = FormatUtil.formatDouble2(ArithUtil.mul(mGroupBean.latest_price, mCurrentItemBean.weight));
                    tv_new_goods_price.setText(goodMoney);
                    initKLine();
                    getKLineFromAPI(mKTimeType, mApiType, mChartCallBack);
                    showLatestPrice();

                    if (mDetailPosition == 0) {
                        initFollowOrder();
                    } else {
                        routeImageActivity();
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                backActivity();
                break;
            case R.id.iv_enter_left:
                changeProGroupBean(true);
                break;
            case R.id.iv_enter_right:
                changeProGroupBean(false);
                break;
            case R.id.iv_buy_up:
                clickBuy(2);
                break;
            case R.id.iv_buy_down:
                clickBuy(1);
                break;
            case R.id.ll_easy_top:
                if (mIsEasy) {
                    mIsEasy = false;
                    setDefaultOrEasy();
                } else {
                    mIsEasy = true;
                    setDefaultOrEasy();
                }
                break;
            case R.id.ll_night_top:
                if (mIsNight) {
                    mIsNight = false;
                    setLightOrDarkBg();
                } else {
                    mIsNight = true;
                    setLightOrDarkBg();
                }
                break;
            case R.id.ll_tab_unit_price:
                mTabIndex = 0;
                changeTab();
                break;
            case R.id.ll_tab_goods:
                mTabIndex = 1;
                changeTab();
                break;
        }
    }

    private void changeTab() {
        if (mTabIndex == 0) {
            ll_tab_unit_price.setBackgroundResource(R.drawable.radio_tab_bean_down_line);
            ll_tab_goods.setBackgroundColor(ContextCompat.getColor(mContext, R.color.transparent));
            mKView.setUnitWeight(1);
        } else {
            ll_tab_unit_price.setBackgroundColor(ContextCompat.getColor(mContext, R.color.transparent));
            ll_tab_goods.setBackgroundResource(R.drawable.radio_tab_bean_down_line);
            if (null != mCurrentItemBean) {
                mKView.setUnitWeight(mCurrentItemBean.weight);
            }
        }
        showLatestPrice();
        getKLineFromAPI(mKTimeType, mApiType, mChartCallBack);
    }


    /**
     * 设置深色模式
     */
    private void setLightOrDarkBg() {
//        ToolbarUtils.setStatusTextColor(false, this);
//        bgColor = ContextCompat.getColor(mContext, R.color.color_black_05);
//        bgTradeColor = ContextCompat.getColor(mContext, R.color.mychart_background);
//        textColor = ContextCompat.getColor(mContext, R.color.white);
//
//        iv_back.setImageResource(R.drawable.ic_back_w);
//        rg_tab_detail.setBackgroundColor(bgColor);
//
//        tv_prepay_order.setTextColor(ContextCompat.getColor(mContext, R.color.color_black_01));
//        tv_empty.setTextColor(ContextCompat.getColor(mContext, R.color.color_black_03));
//        tv_prepay_order.setBackgroundResource(R.drawable.border_round_white_dp4);
////        tv_prepay_order.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_market_prepare_white, 0, 0, 0);
//        setColors();
//        iv_order.setImageResource(R.mipmap.icon_bottom_order_white);
//        nsv_bottom.setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_black_05));
//        ll_goods_bg.setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_black_05));
//        ll_price_range.setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_black_06));
//        ll_last_price.setBackgroundResource(R.drawable.border_color_black_05_6dp);
//        rl_goods_bg.setBackgroundResource(R.drawable.border_color_black_06_12dp);
//        tv_empty.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.iv_empty_dark, 0, 0);
//        if (null != mRVAdapter) {
//            mRVAdapter.setDark(true);
//        }
//        if (null != marketGoodsAdapter) {
//            marketGoodsAdapter.setDark(true);
//        }
//        mKView.setDarkBg();
    }

    /**
     * 设置布局切换
     */
    private void setDefaultOrEasy() {
        ll_easy.setVisibility(mIsEasy ? View.VISIBLE : View.GONE);
        ll_default.setVisibility(mIsEasy ? View.GONE : View.VISIBLE);
        tv_easy_top.setText(mIsEasy ? "标准" : "简洁");
        iv_easy_top.setImageResource(mIsEasy ? R.drawable.ic_default : R.drawable.ic_easy);
        initGoods();
        if (mIsEasy) {
            if (marketGoodsAdapter != null) {
                marketGoodsAdapter.setPosition(mCurrentGoodsPosition);
                rv_goods_easy.smoothScrollToPosition(mCurrentGoodsPosition);
            }
        } else {
            if (marketDefaultPagerAdapter != null) {
                marketDefaultPagerAdapter.setPosition(mCurrentGoodsPosition);
                vp_goods_detail.setCurrentItem(mCurrentGoodsPosition);
            }
        }
    }


    /**
     * 点击购买
     *
     * @param tradeType 购买类型 2现价 1结算价
     */
    private void clickBuy(int tradeType) {
        if (FastClickUtil.isFastClick()) return;
        if (isTradeAble()) {
            if (null != mGroupBean) {
                if (CreateOrderModule.getInstance().getOrderCreateDialog() == null) {
                    //更新用户数据
                    CreateOrderModule.getInstance().createOrderExplain(this, tradeType, "",
                            mGroupBean, mCurrentItemBean.unit_price, "", 0);
                } else {
                    if (!CreateOrderModule.getInstance().getOrderCreateDialog().isShowing()) {
                        //更新用户数据
                        CreateOrderModule.getInstance().createOrderExplain(this, tradeType, "",
                                mGroupBean, mCurrentItemBean.unit_price, "", 0);
                    }
                }
            }
        }
    }

    /**
     * 是否可以交易
     *
     * @return
     */
    private boolean isTradeAble() {
        try {
            if (mGroupBean != null && mGroupBean.during_type == 0) {
                showErrorDialog();
                return false;
            }
            if (!DataUtils.isLogin(mContext)) {
                onLogoutStatus();
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private void showErrorDialog() {
        new PromptDialog.Builder(mContext)
                .setButton("取消", "了解更多")
                .setTitle("已闭市")
                .setOnConfirmListener(new PromptDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        Bundle bundle = new Bundle();
                        bundle.putString("url", Constant.H5_ABOUT_US);
                        bundle.putString("title", "下单问题");
                        gotoActivity(mContext, WebViewActivity.class, bundle);
                    }
                }).show();

    }

    /**
     * @param isLastChoose true上一个，false下一个
     */
    private void changeProGroupBean(final boolean isLastChoose) {
        int dataSize = allList.size();
        if (dataSize == 0) return;
        int index = 0;
        for (int i = 0; i < dataSize; i++) {
            GoodsAllBean bean = allList.get(i);
            if (bean.pro_code.equals(mGroupBean.pro_code)) {
                index = i;
            }
        }
        if (index == 0) {
            if (isLastChoose) {
                mCurrentPro_code = allList.get(dataSize - 1).pro_code;
            } else {
                mCurrentPro_code = allList.get(index + 1).pro_code;
            }
        } else if (index == dataSize - 1) {
            if (isLastChoose) {
                mCurrentPro_code = allList.get(index - 1).pro_code;
            } else {
                mCurrentPro_code = allList.get(0).pro_code;
            }
        } else {
            if (isLastChoose) {
                mCurrentPro_code = allList.get(index - 1).pro_code;
            } else {
                mCurrentPro_code = allList.get(index + 1).pro_code;
            }
        }

        //初始化商品下标
        mCurrentGoodsPosition = 0;
        //初始化历史价格，防止直接变色
        cacheLatestPrice = 0;
        //刷新数据
        initData();
        initGoods();
        showLatestPrice();
        initKLine();
        getKLineFromAPI(mKTimeType, mApiType, mChartCallBack);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //获取当前所有数据
        allList = MyApplication.getApplication().getAllList();
        //获取当前合约对象
        mGroupBean = myApplication.getAllGoodMap().get(mCurrentPro_code);
        //当前商品列表
        if (mGroupBean != null) {
            goods_list = mGroupBean.goods_list;
        }
        if (allList == null || goods_list == null || allList.isEmpty() || goods_list.isEmpty()) return;
        //获取当前商品
        mCurrentItemBean = goods_list.get(mCurrentGoodsPosition);
        if (DataUtils.isLogin(mContext)) {
            myApplication.updateUserDetail();
        }
    }

    /**
     * 初始化商品
     */
    private void initGoods() {
        //设置标题
        tv_title.setText(mGroupBean.pro_name);

        if (mIsEasy) {
            if (marketGoodsAdapter == null) {
                LinearLayoutManager manager = new LinearLayoutManager(this);
                manager.setOrientation(LinearLayoutManager.HORIZONTAL);
                rv_goods_easy.setLayoutManager(manager);
                marketGoodsAdapter = new MarketGoodsAdapter(this, goods_list);
                marketGoodsAdapter.setProGroupBean(mGroupBean);
                rv_goods_easy.setAdapter(marketGoodsAdapter);
                marketGoodsAdapter.setOnItemClickListener(new BaseRVAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(List data, View view, int position, long id) {
                        if (goods_list == null || goods_list.isEmpty()) return;
                        mCurrentGoodsPosition = position;
                        //设置选中
                        marketGoodsAdapter.setPosition(mCurrentGoodsPosition);
                        mCurrentItemBean = goods_list.get(mCurrentGoodsPosition);
                        initKLine();
                        showLatestPrice();

                        if (mDetailPosition == 0) {
                            initFollowOrder();
                        } else {
                            routeImageActivity();
                        }
                    }
                });
            } else {
                marketGoodsAdapter.setData(goods_list);
                marketGoodsAdapter.setProGroupBean(mGroupBean);
                //设置选中
                marketGoodsAdapter.setPosition(mCurrentGoodsPosition);
            }
        } else {
            marketDefaultPagerAdapter = new MarketDefaultPagerAdapter(goods_list, mGroupBean, getLayoutInflater(), vp_goods_detail);
            vp_goods_detail.setAdapter(marketDefaultPagerAdapter);
            vp_goods_detail.setOffscreenPageLimit(4);
        }

        if (mDetailPosition == 0) {
            initFollowOrder();
        } else {
            routeImageActivity();
        }
    }

    /**
     * 初始化k线图
     */
    private void initKLine() {
        mKView.init(this, KViewMode.MODE_KLINE);
        mKView.setLightBg();
        mKView.setProGroupBean(mGroupBean);
        if (mTabIndex == 0) {
            mKView.setUnitWeight(1);//合约，没有重量
        } else {
            mKView.setUnitWeight(mCurrentItemBean.weight);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mKView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mKView.onPause();
    }


    /**
     * 设置商品详情
     */
    private void routeImageActivity() {
        rv_follow_list.setVisibility(View.GONE);
        tv_empty.setVisibility(View.GONE);
        iv_detail.setVisibility(View.VISIBLE);
        if (null == mCurrentItemBean || TextUtils.isEmpty(mCurrentItemBean.product_img)) {
            return;
        }
        String imageUrl = mCurrentItemBean.product_content_img;
        if (TextUtils.isEmpty(imageUrl)) {
            return;
        }
        Glide.with(mContext).load(imageUrl).apply(GlideUtils.getImageDefaultOptions()).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                int width = resource.getIntrinsicWidth();
                int height = resource.getIntrinsicHeight();
                int[] windowWidth = Utils.getWindowWidth(MarketNewActivity.this);

                int wWidth = windowWidth[0];
                Double wHeight = Double.valueOf(windowWidth[1]);

                double scale = wHeight / wWidth;
                if (scale > 1.7f) {
                    double widthScale = Double.valueOf(windowWidth[0]) / width;
                    height = (int) (height * widthScale);
                }

                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(windowWidth[0], height);
                params.setMargins(0, 0, 0, FormatUtil.dp2px(mContext, 40));
                iv_detail.setLayoutParams(params);
                iv_detail.setImageDrawable(resource);
            }
        });
    }

    /**
     * 初始化跟单适配器
     */
    private void initFollowOrder() {
        if (null == mRVAdapter) {
            mFollowOrderList = new ArrayList<>();
            mRVAdapter = new FollowOrderAdapter();
            LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
            rv_follow_list.setLayoutManager(layoutManager);
            rv_follow_list.setAdapter(mRVAdapter);
        }
        getFollowOrderList();
    }

    /**
     * 获取跟单列表数据
     */
    public void getFollowOrderList() {
        rv_follow_list.setVisibility(View.VISIBLE);
        tv_empty.setVisibility(View.GONE);
        iv_detail.setVisibility(View.GONE);

        boolean openTime = false;
        String contract = mGroupBean.pro_code;
        boolean follow = false;
        String level = "";
        int mPageIndex = 1;
        mAppAction.getFollowList(mPageIndex, openTime, contract, follow, level, new ActionCallbackListener<List<FollowOrderBean>>() {
            @Override
            public void onSuccess(List<FollowOrderBean> data) {
                if (data.size() == 0) {
                    rv_follow_list.setVisibility(View.GONE);
                    tv_empty.setVisibility(View.VISIBLE);
                } else {
                    rv_follow_list.setVisibility(View.VISIBLE);
                    tv_empty.setVisibility(View.GONE);

                    mFollowOrderList.clear();
                    mFollowOrderList.addAll(data);
                    updateFollowOrderList();
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });
    }

    /**
     * 刷新跟单列表数据
     */
    private void updateFollowOrderList() {
        if (isScroll) {
            return;
        }
        mRVAdapter.setDataList(Utils.completionFollow(mFollowOrderList));
    }

    /**
     * 设置最新价格
     */
    private void showLatestPrice() {
        if (cacheLatestPrice == mGroupBean.latest_price) return;
        String money = FormatUtil.formatDouble2(mGroupBean.latest_price);//当前原料价格
        String goodMoney = FormatUtil.formatDouble2(ArithUtil.mul(mGroupBean.latest_price, mCurrentItemBean.weight));
        double currentChangeValue = ArithUtil.sub(mGroupBean.latest_price, mGroupBean.price_end_lastday);//增加还是减少具体点数
        double goodsChangeValue = null != mCurrentItemBean ? ArithUtil.mul(currentChangeValue, mCurrentItemBean.weight) : 0;//商品增加减少具体点数
        double currentChangeProportion = 0;
        if (mGroupBean.price_end_lastday != 0) {
            currentChangeProportion = ArithUtil.div(ArithUtil.mul(currentChangeValue, 100), mGroupBean.price_end_lastday, 2);//商品增加幅度
        }

        if (currentChangeValue >= 0) {
            tv_new_goods_price_easy.setTextColor(ContextCompat.getColor(this, R.color.buy_red));
            tv_goods_change_range_easy.setTextColor(ContextCompat.getColor(this, R.color.buy_red));
            tv_new_price.setTextColor(ContextCompat.getColor(this, R.color.buy_red));
            tv_change_range.setTextColor(ContextCompat.getColor(this, R.color.buy_red));
            tv_new_goods_price.setTextColor(ContextCompat.getColor(this, R.color.buy_red));
            tv_goods_change_range.setTextColor(ContextCompat.getColor(this, R.color.buy_red));

            tv_change_range.setText("+" + FormatUtil.formatDouble2(currentChangeValue) + "    +" + currentChangeProportion + "%");
            tv_goods_change_range_easy.setText("+" + FormatUtil.formatDouble2(currentChangeValue) + "    +" + currentChangeProportion + "%");
            tv_goods_change_range.setText("+" + FormatUtil.formatDouble2(goodsChangeValue) + "    +" + currentChangeProportion + "%");
        } else {
            tv_new_goods_price_easy.setTextColor(ContextCompat.getColor(this, R.color.buy_green));
            tv_goods_change_range_easy.setTextColor(ContextCompat.getColor(this, R.color.buy_green));
            tv_new_price.setTextColor(ContextCompat.getColor(this, R.color.buy_green));
            tv_change_range.setTextColor(ContextCompat.getColor(this, R.color.buy_green));
            tv_new_goods_price.setTextColor(ContextCompat.getColor(this, R.color.buy_green));
            tv_goods_change_range.setTextColor(ContextCompat.getColor(this, R.color.buy_green));

            tv_change_range.setText(FormatUtil.formatDouble2(currentChangeValue) + "     " + currentChangeProportion + "%");
            tv_goods_change_range_easy.setText(FormatUtil.formatDouble2(currentChangeValue) + "     " + currentChangeProportion + "%");
            tv_goods_change_range.setText(FormatUtil.formatDouble2(goodsChangeValue) + "     " + currentChangeProportion + "%");
        }
        tv_new_goods_price_easy.setText(money);
        tv_new_price.setText(money);
        tv_new_goods_price.setText(goodMoney);
        if (marketDefaultPagerAdapter != null) {
            marketDefaultPagerAdapter.setLatestPrice(money, goodMoney);
        }

        if (mGroupBean.during_type == 1) {
            ll_create_order.setVisibility(View.VISIBLE);
            rl_close_market.setVisibility(View.GONE);
        } else {
            ll_create_order.setVisibility(View.GONE);
            rl_close_market.setVisibility(View.VISIBLE);
        }

        double calculateTime;
        if (mIsEasy) {
            calculateTime = 1;
        } else {
            if (mTabIndex == 0) {
                calculateTime = 1;
            } else {
                calculateTime = mCurrentItemBean.weight;
            }
        }
        String begin = ArithUtil.format(ArithUtil.mul(mGroupBean.price_beginning, calculateTime));
        String lastDay = ArithUtil.format(ArithUtil.mul(mGroupBean.price_end_lastday, calculateTime));
        String high = ArithUtil.format(ArithUtil.mul(mGroupBean.high_price, calculateTime));
        String low = ArithUtil.format(ArithUtil.mul(mGroupBean.lowwest_price, calculateTime));
        tv_open_easy.setText(begin);
        tv_close_easy.setText(lastDay);
        tv_high_easy.setText(high);
        tv_low_easy.setText(low);
        tv_open.setText("今开：" + begin);
        tv_close.setText("昨收：" + lastDay);
        tv_high.setText("最高：" + high);
        tv_low.setText("最低：" + low);

        if (cacheLatestPrice != 0) {
            if (mGroupBean.latest_price - cacheLatestPrice >= 0) {
                startUpAnim();
            }else {
                startDownAnim();
            }
        }

        //最后赋值，防止初始化变颜色
        cacheLatestPrice = mGroupBean.latest_price;
    }

    /**
     * 开始获取k线图数据
     *
     * @param timeType k线图类型
     * @param callBack 数据成功后回传给view
     */
    @Override
    public void getKLineData(KTimeType timeType, MyChartCallBack callBack) {
        int apiType = 0;
        this.mKTimeType = timeType;
        this.mChartCallBack = callBack;
        Log.e("getKLineData", mKTimeType + "");
        switch (timeType) {
            case MIN1:
                apiType = 1;
                break;
            case MIN_1:
                apiType = 9;
                break;
            case MIN5:
                apiType = 2;
                break;
            case MIN15:
                apiType = 3;
                break;
            case MIN30:
                apiType = 4;
                break;
            case HOUR:
                apiType = 5;
                break;
            case HOUR4:
                apiType = 6;
                break;
            case DAY:
                apiType = 8;
                break;
            case MINI7:
                apiType = 7;
                break;
            case MINI10:
                apiType = 10;
                break;
        }
        this.mApiType = apiType;
        if (mGroupBean != null) {
            getKLineFromAPI(timeType, apiType, callBack);
        }
    }

    @Override
    public void goImageUrl() {

    }

    /**
     * 通过接口获取k线图数据
     *
     * @param timeType
     * @param type
     * @param callBack
     */
    private void getKLineFromAPI(final KTimeType timeType, final int type, final MyChartCallBack callBack) {
        mKLineRefresh = true;
        mAppAction.getKMap(mGroupBean.pro_code, String.valueOf(type), new ActionCallbackListener<List<List<Double>>>() {
            @Override
            public void onSuccess(List<List<Double>> data) {
                if (null != mGroupBean && !TextUtils.isEmpty(mGroupBean.pro_code)) {
                    if (timeType == KTimeType.MIN1) {
                        float close = 0, high = 0, low = 0;
                        if (mGroupBean != null) {
                            close = (float) mGroupBean.price_end_lastday;
                            high = (float) mGroupBean.high_price;
                            low = (float) mGroupBean.lowwest_price;
                        }
                        if (null != callBack) {
                            callBack.onSuccess(generateEntries(data, true), close, high, low, mKTimeType);
                        }
                    } else {
                        if (null != callBack) {
                            float close = 0, high = 0, low = 0;
                            if (mGroupBean != null) {
                                close = (float) mGroupBean.price_end_lastday;
                            }
                            callBack.onSuccess(generateCandleEntries(data, mKTimeType), mKTimeType);
                        }
                    }
                    mKLineRefresh = false;
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                cancelLoading();
                ToastUtil.showToast(mContext, message);
                callBack.onFailed(timeType);
                mKLineRefresh = false;
            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_follow:
                mDetailPosition = 0;
                getFollowOrderList();
                break;
            case R.id.rb_params:
                mDetailPosition = 1;
                routeImageActivity();
                break;
        }
        setTextStyle(mDetailPosition);
    }

    private void setTextStyle(int index) {
        for (int i = 0; i < rg_tab_detail.getChildCount(); i++) {
            RadioButton childAt = (RadioButton) rg_tab_detail.getChildAt(i);
            if (index == i) {
                childAt.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            } else {
                childAt.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            }
        }
    }


    /**
     * 首次计算分时坐标 记录最后一个空值位置
     *
     * @param list
     * @param needSetIndex
     * @return
     */
    private List<Entry> generateEntries(List<List<Double>> list, boolean needSetIndex) {
        mEntries = new ArrayList<>();
        float now;
        List<Double> item;
        for (int i = 0; i < list.size(); i++) {
            item = list.get(i);
            now = Float.parseFloat(String.valueOf(item.get(1)));
            if (i == 0 && now == 0) {
                now = (float) mGroupBean.latest_price;
            }
            mEntries.add(new Entry(i, now, new EntryData(String.valueOf(item.get(0)))));
            if (needSetIndex && now == 0 && mFirstNowZero) {
                mCurrentKLineIndex = i - mIndexOffset > 0 ? i - mIndexOffset : 0;
                mFirstNowZero = false;
            }
        }
        mFirstNowZero = true;
        return mEntries;
    }

    private List<CandleEntry> generateCandleEntries(List<List<Double>> list, KTimeType timeType) {
        List<CandleEntry> entries = new ArrayList<>();
        int x = 0;
        String time;
        List<Double> item;
        for (int i = 0; i < list.size(); i++) {
            item = list.get(i);
            if (!item.isEmpty()) {
                LogUtil.d("dzt", "第一个：" + item.get(0) + "第二个" + item.get(1));
                try {
                    if (timeType == KTimeType.DAY) {
                        time = dateFormat.format(new Date(item.get(0).longValue() * 1000));
                    } else {
                        time = timeFormat.format(new Date(item.get(0).longValue() * 1000));
                    }
                    entries.add(new CandleEntry(x++,
                            Float.parseFloat(String.valueOf(item.get(2))),
                            Float.parseFloat(String.valueOf(item.get(3))),
                            Float.parseFloat(String.valueOf(item.get(1))),
                            Float.parseFloat(String.valueOf(item.get(4))),
                            new EntryData(time, String.valueOf(item.get(0).longValue() * 1000))));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        //timeType == KTimeType.DAY &&
        if (entries.size() > 0) {
//            updateDayEntry(entries);
        }
        return entries;
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        super.onEventComming(eventCenter);
        int event = eventCenter.getEventCode();
        switch (event) {
            case EventConstants.EVENTCODE_UPDATE_USER:
                if (null != marketGoodsAdapter) {
                    marketGoodsAdapter.notifyDataSetChanged();
                }
                if (null != CreateOrderModule.getInstance().getOrderCreateDialog() && CreateOrderModule.getInstance().getOrderCreateDialog().isShowing()) {
                    CreateOrderModule.getInstance().getOrderCreateDialog().refreshBalance();
                }
                break;
            case EventConstants.EVENTCODE_UPDATE_PRO_PRICE:
                showLatestPrice();

                if (mGroupBean != null) {
                    if (null != CreateOrderModule.getInstance().getOrderCreateDialog()
                            && CreateOrderModule.getInstance().getOrderCreateDialog().isShowing()) {
                        CreateOrderModule.getInstance().getOrderCreateDialog().setNewPrice();
                    }
                }
                break;
            case EventConstants.EVENTCODE_UPDATE_PRO_FOLLOW_PRICE:
                if (isScroll) return;
                updateFollowOrderList();
                break;
        }
    }

    private void setPriceAnimtion() {
        hideAnimation = new AnimationSet(true);
        hideAnimation.setDuration(DURATION_TIME);
        AlphaAnimation alphadown = new AlphaAnimation(1, 0);
        alphadown.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view_bg.setBackgroundColor(Color.TRANSPARENT);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        hideAnimation.addAnimation(alphadown);

        showAnimation = new AnimationSet(true);
        showAnimation.setDuration(DURATION_TIME);
        AlphaAnimation alpha = new AlphaAnimation(0, 1);
        alpha.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view_bg.startAnimation(hideAnimation);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        showAnimation.addAnimation(alpha);
    }

    private void startUpAnim() {
        view_bg.setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_33F24957));
        view_bg.startAnimation(showAnimation);
    }

    private void startDownAnim() {
        view_bg.setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_331DBF60));
        view_bg.startAnimation(showAnimation);
    }

}
